<template>
  <div>
    <el-container style="flex-wrap: wrap;">
      <!-- 头部导航栏 -->
      <BreadHeader></BreadHeader>
      <!-- 主题内容 -->
      <XPannel>
        <!-- 标题头部部分 -->
        <template v-slot:header>
          <span>部门管理</span>
          <el-button
            type="primary"
            plain
            style="float: right; padding: 10px 20px; margin-left: 15px"
            @click="adduser"
            >点击添加部门</el-button
          >
        </template>
        <!-- 列表内容部分 -->
        <template v-slot:default>
          <!-- 添加抽屉 -->
          <el-drawer
            title="添加部门"
            :visible.sync="draweradd"
            ref="drawer"
            :show-close="true"
            style="text-align: center;"
          >
            <el-form
              :model="addruleForm"
              :rules="rulesadd"
              ref="addruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item
                label="部门名"
                prop="addpname"
                style="width: 400px; margin: 20px auto"
              >
                <el-input
                  placeholder="请输入部门名"
                  v-model="addruleForm.addpname"
                  clearable
                  style="width: 300px; display: block"
                >
                </el-input>
              </el-form-item>
              <el-form-item
                label="部门状态"
                style="width: 400px; margin: 20px auto"
                prop="addstatus"
              >
                <el-select
                  v-model="addruleForm.addstatus"
                  placeholder="请选择"
                  style="width: 300px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <!-- @click="submitForm('ruleForm')" -->
            <el-button
              type="primary"
              @click="submitadd('addruleForm')"
              style="padding: 10px 20px; margin: 5px;"
              >确认添加</el-button
            >
            <el-button
              type="info"
              @click="resetForm('addruleForm')"
              style="padding: 10px 20px; margin: 5px"
              >重置已填</el-button
            >
          </el-drawer>
          <!-- 部门列表 -->
          <el-table
            ref="multipleTable"
            :data="partlist"
            tooltip-effect="dark"
            style="width: 100%; margin: auto"
            @selection-change="handleSelectionChange"
            height="380"
          >
            <el-table-column label="全选" type="selection" width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="180">
            </el-table-column>
            <el-table-column prop="pname" label="部门名称" width="180">
            </el-table-column>
            <el-table-column prop="status" label="部门状态" width="180">
            </el-table-column>
            <el-table-column prop="caozuo" label="操作">
              <template #default="scope">
                <el-button
                  @click="xiugaiobtain(scope.row)"
                  type="primary"
                  style="margin-left: 16px; padding: 5px 10px"
                >
                <i class="el-icon-edit"></i>
                编辑
                </el-button>
                <el-button
                  type="danger"
                  @click="open(scope.row)"
                  style="padding: 5px 10px"
                  ><i class="el-icon-delete"></i>
                  删除</el-button
                >
                <el-drawer
                  title="修改部门名称区"
                  :visible.sync="drawer"
                  :show-close="true"
                  ref="drawer_edit"
                  style="text-align: center;"
                >
                  <el-form
                    :model="editruleFrom"
                    :rules="rulesedit"
                    ref="editruleFrom"
                    label-width="100px"
                    class="demo-ruleForm"
                  >
                    <el-form-item
                      label="部门名"
                      prop="pnamesave"
                      style="margin: 20px; width: 80%; margin: 30px auto"
                    >
                      <el-input
                        placeholder="请输入部门名"
                        v-model="editruleFrom.pnamesave"
                        clearable
                        style="width: 300px; display: block"
                      >
                      </el-input>
                    </el-form-item>
                    <el-form-item
                      label="部门状态"
                      prop="statussave"
                      clearable
                      style="margin: 20px; width: 80%; margin: 30px auto"
                    >
                      <el-select
                        v-model="editruleFrom.statussave"
                        placeholder="请选择"
                        style="width: 300px; display: block"
                      >
                        <el-option
                          v-for="item in editoptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                  <el-button
                    type="success"
                    @click="submit('editruleFrom')"
                    style="padding: 10px 20px; margin: 5px;"
                    >确认修改</el-button
                  >
                  <el-button
                    type="info"
                    @click="reset"
                    style="padding: 10px 20px; margin: 5px"
                    >重置已填</el-button
                  >
                </el-drawer>
              </template>
            </el-table-column>
          </el-table>
          <!-- 批量操作 -->
          <div class="piliang" style="width: 300px; background: #ffffff">
            <el-button
              type="danger"
              @click="batchDelete"
              style="padding: 10px 15px; margin: 20px 0px"
              >批量删除</el-button
            >
            <el-button
              @click="toggleSelection()"
              type="primary"
              style="padding: 10px 15px; margin: 20px 10px"
              >取消选择</el-button
            >
            <!-- <el-button @click="clearSelection">取消批量</el-button> -->
          </div>
          <!-- 页码显示 -->
          <div class="block" style="padding: 5px;width: 450px;margin: auto;">
            <el-pagination
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalUsers"
              @size-change="handleChangeSize"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </template>
      </XPannel>
    </el-container>
  </div>
</template>

<script>
import BreadHeader from "@/components/BreadHeader.vue";
import http from "../api/http";
import XPannel from "@/components/XPannel.vue";
import { mapState } from "vuex";

export default {
  components: {
    XPannel,
    BreadHeader
  },
  computed: {
    ...mapState(["name","picture"]),
    userName() {
      return this.name;
    },
    userPicture() {
      return this.picture;
    },
  },
  data() {
    return {
      draweradd: false,
      partlist: [],
      addruleForm: {
        addpname: "",
        addstatus: null,
      },
      rulesadd: {
        addpname: [
          { required: true, message: "请输入部门名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        addstatus: [
          { required: true, message: "请选择此部门状态", trigger: "change" },
        ],
      },
      options: [
        {
          value: 1,
          label: "启用",
        },
        {
          value: 0,
          label: "禁用",
        },
      ],
      value: "",
      editoptions: [
        {
          value: 1,
          label: "启用",
        },
        {
          value: 0,
          label: "禁用",
        },
      ],
      editvalue: "",
      deluserid: null,
      editruleFrom: {
        pnamesave: "",
        statussave: 0,
      },
      rulesedit: {
        pnamesave: [
          { required: true, message: "请输入部门名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        statussave: [
          { required: true, message: "请选择此部门状态", trigger: "change" },
        ],
      },
      drawer: false,
      xiugaiobtainuid: null,
      totalUsers: 0, //总数
      pageSize: 5, //每页条数
      pageNum: 1, //当前页码
      selected: [],
    };
  },
  methods: {
    // 抽屉取消
    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then(() => {
    //       this.draweradd = false;
    //       done();
    //     })
    //     .catch(() => {});
    // },
    // 跳转到修改信息页面
    xiugaiobtain(row) {
      this.drawer = true;
      console.log(row.id);
      http
        .get("department/edit/" + row.id)
        .then((response) => {
          console.log(response);
          this.xiugaiobtainuid = response.data.id;
          this.editruleFrom.pnamesave = response.data.pname;
          this.editruleFrom.statussave = response.data.status;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    submitadd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.adduserfn();
          this.resetadd();
          this.draweradd = false;
          this.$message({
          message: '恭喜你，部门添加成功！',
          type: 'success'
        });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submit(editruleFrom) {
      this.$refs[editruleFrom].validate((valid) => {
        if (valid) {
          this.$message({
          message: '恭喜你，部门修改成功！',
          type: 'success'
        });
          http
            .post("department/save_edit/" + this.xiugaiobtainuid, {
              pname: this.editruleFrom.pnamesave,
              status: this.editruleFrom.statussave,
            })
            .then((response) => {
              console.log(response);
              this.userlistfn();
              this.drawer = false;
            })
            .catch((error) => {
              console.log(error);
            });
          this.drawer = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleChangeSize(data) {
      this.pageSize = data;
      this.userlistfn();
    },
    handleCurrentChange(data) {
      this.pageNum = data;
      this.userlistfn();
    },
    // partlistfn() {
    //   http
    //     .get("department/list")
    //     .then((response) => {
    //       console.log(response);
    //       this.partlist = response.data;
    //     })
    //     .catch((error) => {
    //       console.log(error);
    //     });
    // },
    // 列表方法
    userlistfn() {
      http
        .get("/department/list", {
          params: {
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          console.log(response.data);
          // this.userlist.push(response.data)
          this.partlist = response.data.list;
          console.log(this.partlist);
          this.totalUsers = response.data.totalNum;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    batchDelete() {
      if (this.selected.length === 0) {
        this.$message({
          message: "请先选择要删除的项",
          type: "warning",
        });
        return;
      }
      this.$confirm("此操作将永久删除选中的部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 批量删除---代办--ok
          this.selected.forEach((item) => {
            // const index = this.userlist.indexOf(item);
            let deluserids = [];
            deluserids.push(item.id);
            let deluseridsting = JSON.stringify(deluserids);
            http
              .get("/department/deletes/" + deluseridsting)
              .then((response) => {
                console.log(response);
              })
              .catch((error) => {
                console.log(error);
              });
            this.userlistfn();
            // this.userlist.splice(index, 1);
          });
          this.selected = []; // 清空选中的项
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      this.selected = val;
      console.log(this.selected);
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // handleSelectionChange(val) {
    //   this.multipleSelection = val;
    // },
    adduser() {
      this.draweradd = true;
    },

    changeRadio(data) {
      this.upartsave = data;
    },
    directcloseadd() {
      this.$confirm(
        "检测到未保存的内容，是否在离开页面前保存添加？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "保存",
          cancelButtonText: "放弃添加",
        }
      )
        .then(() => {
          this.adduserfn();
          this.$message({
            type: "info",
            message: "保存添加",
          });
        })
        .catch((action) => {
          // this.draweradd = false
          this.$message({
            type: "info",
            message:
              action === "cancel" ? "放弃添加并离开页面" : "停留在当前页面",
          });
          if (action === "cancel") {
            this.draweradd = false;
            this.resetadd();
          }
        });
    },
    adduserfn() {
      http
        .post("/department/add", {
          // params: {
          pname: this.addruleForm.addpname,
          status: this.addruleForm.addstatus,
          // },
        })
        .then((response) => {
          console.log(response);
          this.userlistfn();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    resetadd() {
      this.addruleForm.addpname = "";
      this.addruleForm.addstatus = 1;
    },
    open(row) {
      this.$confirm("此操作将永久删除该部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(1, row);
          // this.deluserid = this.userlist[row].id
          this.deluserid = row.id;
          this.deleteuserfn();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.userlistfn();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteuserfn() {
      http
        .get("/department/delete/" + this.deluserid)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    directclose() {
      this.$confirm(
        "检测到未保存的内容，是否在离开页面前保存修改？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "保存",
          cancelButtonText: "放弃修改",
        }
      )
        .then(() => {
          this.submit();
          this.$message({
            type: "info",
            message: "保存修改",
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message:
              action === "cancel" ? "放弃保存并离开页面" : "停留在当前页面",
          });
          if (action === "cancel") {
            this.drawer = false;
          }
        });
    },
    reset() {
      this.editruleFrom.pnamesave = "";
      this.editruleFrom.statussave = 1;
    },
  },
  created() {
    this.userlistfn();
  },
};
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>